from django.shortcuts import render, redirect, HttpResponse
from web.forms.commodity import GoodModelForm
from django.http import JsonResponse
from django.core.files.storage import FileSystemStorage
from django.conf import settings
import os
from web import models

import hashlib
import random
import time


def generate_gid(usrid):
    # 获取当前时间戳，精确到秒
    timestamp = int(time.time())

    # 生成一个6位的随机数
    random_number = random.randint(100000, 999999)

    # 将时间戳和随机数拼接成字符串
    gid_string = f"{usrid}{timestamp}{random_number}"

    # 使用哈希算法（这里使用MD5）生成32位的哈希值
    hash_object = hashlib.md5(gid_string.encode())
    hash_value = hash_object.hexdigest()

    # 截取前32位作为GID
    gid = hash_value[:32]

    return gid


def goods_list(request):
    """ 列表显示 """
    if request.method == 'GET':
        goods_dict = {'my': models.Good.objects.filter(owner=request.user_obj), 'log': models.Transaction.objects.filter(owner=request.user_obj).all()[:10]}
        form = GoodModelForm()
        context = {
            'form': form,
            'goods_dict': goods_dict
        }
        return render(request, 'commodity_list.html', context)

    gid = generate_gid(request.session.get('user_id', 0))
    form = GoodModelForm(gid, data=request.POST, files=request.FILES)
    print(request.POST)
    if form.is_valid():
        # 添加项目
        form.instance.owner = request.user_obj
        form.instance.buy = 0
        form.instance.views = 0
        form.instance.stars = 0
        form.instance.Good_ID = generate_gid(request.session.get('user_id', 0))
        form.save()

        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def goods_modify(request, good_id):
    if request.method == 'GET':
        return redirect('wiki')
    data = request.POST
    if data['type'] == 'del':
        good = models.Good.objects.filter(Good_ID=good_id).first()
        image = good.image
        if os.path.exists(image.path):
            os.remove(image.path)
            # print(image.path)
        good.delete()
        return JsonResponse({'status': True})
    if data['type'] == 'modify':
        file = request.FILES
        good = models.Good.objects.filter(Good_ID=good_id).first()
        name = data['name']
        desc = data['desc']
        stock = data['stock']
        gtype = data['gtype']
        print(gtype)
        if name:
            good.name = name
        if desc:
            good.desc = desc
        if stock:
            good.stock = stock

        good.type = gtype
        if file:
            file = file['image']
            fs = FileSystemStorage()
            rpath = 'commodity/'+good.Good_ID
            file_path = os.path.join(settings.MEDIA_ROOT, rpath)
            if os.path.exists(file_path):
                os.remove(file_path)
            fs.save(rpath, file)

        good.save()
        return JsonResponse({'status': True})

    return JsonResponse({'status': False, 'error': {'details': 'Unknown error'}})
